<template>
  <div class="login flex  flex-align-center flex-column">
    <img src="../../assets/img/login/logo.png" class="logo-style"/>

    <div class="loginForm mt-10">
      <div class="form-header flex tabHeader flex-justify-content-around">
        <div class="tips">账号登录</div>
      </div>
      <div class="form-content ">
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="0"
            class="demo-ruleForm el-formC"
        >
          <el-form-item label="" prop="username">
            <div class="flex flex-align-center width100">
              <img src="../../assets/img/login/user.png" class="icon-style mr-4">
              <el-input v-model="ruleForm.username" type="text" autocomplete="off" class="flex1" clearable
                        placeholder="请输入用户名"/>
            </div>
          </el-form-item>
          <el-form-item label="" prop="pwd">
            <div class="flex flex-align-center width100">
              <img src="../../assets/img/login/pass.png" class="icon-style mr-4">
              <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" class="flex1" clearable
                        placeholder="请输入密码"/>
            </div>

          </el-form-item>
          <el-form-item label="" prop="vaildcode">
            <div class="flex flex-align-center width100">
              <img src="../../assets/img/login/check.png" class="icon-style mr-4">
              <el-input v-model="ruleForm.vaildcode" type="text" autocomplete="off" class="flex1" clearable
                        placeholder="请输入验证码"/>
              <div class="identifyBox" @click="refreshCode">
                <img :src="validationObj?.base64" class="identifyImg"/>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex flex-justify-content-center width100">
              <el-button type="primary" @click="submitForm(ruleFormRef)" class="width100"
              >登录
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div class="rememberPwd">
          <el-checkbox size="large" v-model="rememberPwd">记住密码</el-checkbox>
        </div>
      </div>

    </div>

  </div>
</template>

<script lang="ts" setup>
//组件
import {ElMessage} from 'element-plus'
//接口


//api
import {reactive, ref, onBeforeMount, onMounted} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {useRoute, useRouter} from "vue-router";
import useUserStore from "@/store/modules/user/user";
//@ts-ignore
import md5 from "js-md5";
import type {cptChaRes, loginParams} from "@/api/login/type";
import {getCaptcha} from "@/api/login";
import * as events from "events";

//data
let userStore = useUserStore()
let route = useRoute()
let router = useRouter()
const ruleFormRef = ref<FormInstance>()
let userLoginMsg = window.localStorage.getItem('userLoginMsg') ? JSON.parse(window.localStorage.getItem('userLoginMsg')!) : {}
const ruleForm = reactive({
  username: userLoginMsg.username,
  pwd: userLoginMsg.pwd,
  vaildcode: '',
})
const rememberPwd = ref<boolean>(userLoginMsg.username ? true : false)
//验证码
const validationObj = ref<cptChaRes>()
window.localStorage.setItem('from','new')

/****************************函数****************************/

/**************************接口函数**************************/
//登录接口
const loginHandle = () => {
  let params: loginParams = {
    captchaCode: ruleForm.vaildcode,
    captchaKey: validationObj.value!.captchaKey,
    pwd: md5(ruleForm.pwd),
    username: ruleForm.username
  }
  return userStore.login(params)
}


/**************************操作函数**************************/
//用户名form判断
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

//密码form判断
const validateUserName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号名'))
  } else {
    callback()
  }
}

//验证码form判断
const validateVaildcode = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else {
    callback()
  }
}

//登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      loginHandle().then((res) => {
        if (res.code === 0) {
          if (rememberPwd.value) {
            window.localStorage.setItem('userLoginMsg', JSON.stringify({
              pwd: ruleForm.pwd,
              username: ruleForm.username
            }))
          } else {
            window.localStorage.removeItem('userLoginMsg')
          }
          router.push('/home')
          ElMessage({
            message: '登录成功',
            type: 'success',
          })
        } else {
          refreshCode()
          ElMessage({
            message: res.msg,
            type: 'error',
          })
        }
      }).catch((err) => {
        refreshCode()
        ElMessage({
          message: err.msg,
          type: 'error',
        })
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const rules = reactive<FormRules<typeof ruleForm>>({
  pwd: [{validator: validatePass, trigger: 'blur'}],
  username: [{validator: validateUserName, trigger: 'blur'}],
  vaildcode: [{validator: validateVaildcode, trigger: 'blur'}],
})

//刷新验证码
const refreshCode = () => {
  useGetCaptcha()
}

//请求验证码
const useGetCaptcha = async () => {
  let res = await getCaptcha()
  validationObj.value = res.data
}

const keyDown = (e:KeyboardEvent)=>{
  if(e.key==='Enter'){
    submitForm(ruleFormRef.value)
  }
}

window.addEventListener('keydown',keyDown)
useGetCaptcha()
</script>


<style scoped lang="scss">
.login {
  width: 100%;
  min-height: 100%;
  background-image: url("../../assets/img/login/homebg2.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  position: relative;

  .logo-style {
    width: 825px;
    height: 105px;
    margin-top: 57px;
  }

  .loginForm {
    width: 580px;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.3);
    border-radius: 10px;

    .form-header {
      width: 100%;
      height: 100px;
      align-items: center;
      justify-content: center;

      .tips {
        color: rgba(66, 66, 66, 1);
        font-size: 22px;
        font-weight: bold;
      }
    }

    .form-content {
      padding: 45px;
      height: 100%;
      background-color: #E0F3FE;
      border-radius: 0 0 10px 10px;

      .identifyBox {
        width: 150px;
        height: 40px;
        margin-left: 20px;

        .identifyImg {
          display: block;
          width: 100%;
          height: 100%;
        }
      }
    }

    .icon-style {
      width: 40px;
      height: 40px;
    }
  }
}


</style>
